<script setup lang="ts">
import { computed } from 'vue';
import useUpload from './hooks/use-upload';

const {
  handleFileChange,
  handleUploadFile,
  handlePause,
  fileChunks,
  file,
  hashPercentage,
  isPaused,
  handleResume,
} = useUpload();

const uploadPercentage = computed(() => {
  if (!file.value) {
    return 0;
  }

  const process = fileChunks.value.reduce((acc, cur) => {
    acc += cur.percentage * cur.chunk.size;
    return acc;
  }, 0);

  const percentage = Math.round(process / file.value?.size);

  return percentage;
});
</script>

<template>
  <input
    type="file"
    @change="handleFileChange"
  />
  <ElButton @click="handleUploadFile">Upload</ElButton>
  <ElButton
    :disabled="isPaused"
    @click="handlePause"
  >
    Pause
  </ElButton>
  <ElButton
    :disabled="!isPaused"
    @click="handleResume"
  >
    Resume
  </ElButton>
  <div>
    <ElText
      class="mx-1"
      type="primary"
    >
      上传进度
    </ElText>
    <ElProgress
      :percentage="uploadPercentage"
      :status="uploadPercentage === 100 ? 'success' : ''"
    />
    <ElText
      class="mx-1"
      type="primary"
    >
      hash 进度
    </ElText>
    <ElProgress
      :percentage="hashPercentage"
      :status="hashPercentage === 100 ? 'success' : ''"
    />
    <ElRow>
      <ElCol :span="8">
        <div class="grid-content ep-bg-purple" />
        chunk hash
      </ElCol>
      <ElCol :span="6">
        <div class="grid-content ep-bg-purple" />
        size(Kb)
      </ElCol>
      <ElCol :span="6">
        <div class="grid-content ep-bg-purple" />
        percentage
      </ElCol>
    </ElRow>

    <ElRow
      v-for="chunk in fileChunks"
      :key="chunk.hash"
    >
      <ElCol :span="8">{{ chunk.hash }}</ElCol>
      <ElCol :span="6">{{ (chunk as any).chunk.size }} </ElCol>
      <ElCol :span="6">
        <ElProgress
          :percentage="chunk.percentage"
          :status="chunk.percentage === 100 ? 'success' : ''"
        />
      </ElCol>
    </ElRow>
  </div>
</template>
;
